package common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissionFilter implements Filter{

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		String servletPath=req.getServletPath();
		HttpSession session=req.getSession();
		String flag=(String) session.getAttribute("flag");
		System.out.println(servletPath);
		System.out.println(servletPath!=null&&(servletPath.equals("/index.jsp"))||(servletPath.equals("/login.jsp"))||(servletPath.equals("/login.do")));
		if(servletPath!=null&&(servletPath.equals("/index.jsp"))||(servletPath.equals("/login.jsp"))||(servletPath.equals("/login.do"))){
			chain.doFilter(req, resp);
		}else{
			System.out.println(flag);
			if(flag!=null&&flag.equals("login_success")){
				chain.doFilter(req, resp);
			}else if(flag!=null&&flag.equals("login_error")){
				req.setAttribute("msg", "登陆失败");
				req.setAttribute("return_url", servletPath);
				RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
				rd.forward(req, resp);
			}else{
				req.setAttribute("msg", "您尚未登陆");
				req.setAttribute("return_uri", servletPath);
				System.out.println("out");
				RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
				rd.forward(req, resp);
			}
		}
	}

	
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
